package com.weilive.api;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;

import com.weilive.core.command.Command;
import com.weilive.core.command.Command.Executor;
import com.weilive.core.command.CommandManager;
import com.weilive.core.common.CallBack;
import com.weilive.core.common.SharedTimer;

public class ResourceManager {
	private static final long PERIOD = 30 * 1000L;
	private static final List<CallBack> RELOAD_RESOURCE = new ArrayList<CallBack>();

	private ResourceManager() {

	}

	public static void loadBySpring(ApplicationContext context) {

		CommandManager.registerExecutor("reloadServer", new Executor() {
			@Override
			public int getPriority() {
				return 1;
			}

			@Override
			public String exec(Command command) {
				reloadData();
				return "ok";
			}
		});

		SharedTimer.schedule(new Runnable() {

			@Override
			public void run() {
				reloadData();

			}
		}, PERIOD, PERIOD);
	}

	public static synchronized void register(String func, Class<?> clazz, Object obj) {
		try {
			Method m = clazz.getMethod(func);
			CallBack callback = new CallBack(obj, m);
			RELOAD_RESOURCE.add(callback);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void reloadData() {
		for (CallBack callback : RELOAD_RESOURCE) {
			try {
				callback.getMethod().invoke(callback.getObj());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
